<?php


namespace App\Http\Controllers\Api\frontend;

use App\Http\Controllers\Api\BaseApiController;
use App\Models\HhmOrder;
use App\Models\HhmOrderGoods;
use App\Models\HhmGoods;
use App\Models\LoveMember;
use App\Models\Member;
use App\Models\BreedConsume;
use App\Models\BreedUserCoin;
use App\Models\StoreCashierSwitchCodeGroupRelation;
use App\Models\StoreCashierSwitchCodeGroupProperties;
use App\Models\StoreCashierSwitchCodeGroup;
use App\Models\DistrictAgentCommissionConfig;
use App\Models\StaffAuth;
use App\Models\HhmVendorVerifiy;
use App\Common\CreateRandomNumber;
use Illuminate\Support\Facades\DB;
use App\Services\CreditPay;
use App\Models\Store;
use App\Services\OrderCommonService;
use App\Services\OrderPayService;
use app\common\exceptions\AppException;
use App\Models\LoveRecords;
use App\Models\BreedUserCoinQuota;
use App\Models\BreedCoinQuotaFlow;
use App\Models\HhmCoinCorpQuota;
use App\Services\CropQuotaService;
class OrderController extends BaseApiController
{
    /**
     * @var MemberCartCollection
     */

    protected function validateParam()
    {
        // 从 param 对象中获取参数（统一格式）
        $param = request()->input('param');
        
        \Log::info('[创建订单] 验证参数:', ['param' => $param]);
        
        if(!$param || !isset($param['uid']) || !isset($param['price']) || 
           !isset($param['goods_price']) || !isset($param['goods_total']) || 
           !isset($param['goods']) || !isset($param['store_id'])){
            \Log::error('[创建订单] 参数验证失败，缺少必填字段');
            return response()->json([
                'code' => 400,
                'message' => '请求参数有误',
                'data' => null
            ]);
        }
    }

    /**
     * 创建订单
     * @return \Illuminate\Http\JsonResponse
     * @throws \app\common\exceptions\AppException
     */
    public function index()
    {
        \Log::info('[创建订单] ========== 开始创建订单 ==========');
        
        // 获取完整请求数据（用于日志）
        $fullRequest = request()->input();
        \Log::info('[创建订单] 接收到的完整请求:', $fullRequest);
        
        // 从 param 对象中获取参数（统一格式）
        $data = request()->input('param');
        \Log::info('[创建订单] 解析后的订单参数:', $data);
        
        // 验证参数
        $this->validateParam();
        \Log::info('[创建订单] 参数验证通过');
        
        // 创建订单（使用事务）
        try {
            $result = DB::transaction(function () use ($data) {
                \Log::info('[创建订单] 开始事务处理');
                
                // 1. 创建订单主记录
            $order = new HhmOrder();
            $order->fill($data);
            $order_sn = self::createOrderSN();
            $order['order_sn'] = $order_sn;
                
                // 补充必填字段的默认值
                $order['dispatch_price'] = $data['dispatch_price'] ?? 0.00;
                $order['discount_price'] = $data['discount_price'] ?? 0.00;
                $order['order_goods_price'] = $data['order_goods_price'] ?? $data['goods_price'];
                $order['deduction_price'] = $data['deduction_price'] ?? 0.00;
                $order['change_price'] = $data['change_price'] ?? 0.00;
                $order['change_dispatch_price'] = $data['change_dispatch_price'] ?? 0.00;
                $order['cost_amount'] = $data['cost_amount'] ?? 0.00;
                $order['fee_amount'] = $data['fee_amount'] ?? 0.00;
                $order['service_fee_amount'] = $data['service_fee_amount'] ?? 0.00;
                $order['dkfee'] = $data['dkfee'] ?? 0.00;
                // 注意：payment_amount 字段在 ims_hhm_order 表中不存在，已移除
                
                \Log::info('[创建订单] 补充默认值后的订单数据:', $order->toArray());
                
                \Log::info('[创建订单] 生成订单号:', ['order_sn' => $order_sn]);
                \Log::info('[创建订单] 订单数据:', $order->toArray());
                
            if ($order->save()) {
                    \Log::info('[创建订单] 订单主记录保存成功，订单ID:', ['order_id' => $order->id]);
                    
                    // 2. 重新查询订单以获取完整数据
                $order = HhmOrder::where('order_sn',$order_sn)->first();
                $orderId = $order->id;
                $goods = $data['goods'];
                    
                    \Log::info('[创建订单] 商品列表:', ['goods_count' => count($goods), 'goods' => $goods]);
                    
                if(!count($goods)){
                        \Log::error('[创建订单] 商品参数有误：商品列表为空');
                        throw new \Exception('商品参数有误');
                }
                    
                    // 3. 创建订单商品记录
                    foreach ($goods as $index => $item) {
                        \Log::info("[创建订单] 处理商品 #{$index}:", $item);
                        
                        // 查询商品信息
                        $HhmGoods = HhmGoods::where('id', $item['id'])
                            ->first();
                            
                        if (!$HhmGoods) {
                            \Log::error("[创建订单] 商品不存在:", ['goods_id' => $item['id']]);
                            throw new \Exception("商品ID {$item['id']} 不存在");
                        }
                        //扣库存方式0下单1付款2永不
                        $stock = $HhmGoods->stock;
                        $reduce_stock_method = $HhmGoods->reduce_stock_method;
                        if($reduce_stock_method==0){
                            $stock = $stock-$item['total'];
                        }
                        $HhmGoods->stock =  $stock;
                        $HhmGoods->save();
                        \Log::info("[创建订单] 查询到商品信息:", [
                            'goods_id' => $HhmGoods->id,
                            'title' => $HhmGoods->title,
                            'price' => $HhmGoods->price
                        ]);
                        
                        // 创建订单商品记录
                        $orderGoodsData = [
                        'order_id' => $orderId,
                        'goods_id' => $item['id'],
                        'total' => $item['total'],
                        'price' => $HhmGoods->price,
                        'uid' => $data['uid'],
                        'thumb' => $HhmGoods->thumb,
                        'title' => $HhmGoods->title,
                            'cost_price' => $HhmGoods->cost_price ?? 0.00,
                            'market_price' => $HhmGoods->market_price ?? 0.00,
                            // 补充必填字段的默认值
                            'goods_price' => $HhmGoods->price,
                            'discount_price' => 0.00,
                            'change_price' => 0.00,
                            'payment_amount' => 0.00,
                            'deduction_amount' => 0.00,
                            'comment_status' => 0,
                            'goods_option_id' => $item['goods_option_id'] ?? 0,
                            'goods_option_title' => $item['goods_option_title'] ?? '',
                            'comment_id' => 0,
                            'need_address' => 0,
                            'is_refund' => 0,
                        ];
                        
                        $orderGoodsRecord = HhmOrderGoods::create($orderGoodsData);
                        \Log::info("[创建订单] 订单商品记录创建成功:", [
                            'order_goods_id' => $orderGoodsRecord->id,
                            'goods_id' => $item['id'],
                            'total' => $item['total']
                    ]);
                }
                    
                    \Log::info('[创建订单] 所有商品记录创建完成');
                } else {
                    \Log::error('[创建订单] 订单主记录保存失败');
                    throw new \Exception('订单保存失败');
            }
                
                \Log::info('[创建订单] 事务处理完成，返回结果');
                
            return [
                'order' => $order,
                'order_id' => $order->id,
            ];
        });
            
            \Log::info('[创建订单] ========== 订单创建成功 ==========', [
                'order_id' => $result['order_id'],
                'order_sn' => $result['order']->order_sn
            ]);
            
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => [
                    'order_id' => $result['order_id'],
                    'order' => $result['order']
                ]
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[创建订单] ========== 订单创建失败 ==========', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '创建订单失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
    }
    }

    public function credit()
    {
        // 从 param 对象中获取参数（统一格式）
        $param = request()->input('param');
        
        $pay_type = $param['pay_type'] ?? 0;
        $order_id = $param['order_id'] ?? 0;
        $uid = $param['uid'] ?? 0;
        $pid = $param['pid'] ?? $uid;  // pid默认等于uid
        
        $order = HhmOrder::where('id', $order_id)->first();
        if (!$order) {
            return response()->json([
                'code' => 400,
                'message' => '订单不存在',
                'data' => null
            ]);
        }
        
        $store_id = $order->store_id;
        $price = $order->price;
        
        $params = [
            'member_id' => $uid,
            'amount' => $price,
            'order_sn' => $order->order_sn,
            'operator_id' => $uid,  // 操作者ID（当前用户）
        ];
        
        if($pay_type!=133&&$pay_type!=137&&$pay_type!=138){
            return response()->json([
                'code' => 400,
                'message' => '支付类型pay_type错误',
                'data' => null
        ]);
        }
        
        // 定义 user_id（用于后续结算）
        $user_id = $uid;
        
        if($pay_type ==137){ //是沐浴露支付
            //先查出设置的支持哪种沐浴露
            $breedConsumes = BreedConsume::where(['is_swap'=>1])->get();
            
            $userCoin = 0;
            
            //算出用户沐浴露是否足够
            foreach($breedConsumes as $breedConsume){
                $record = BreedUserCoin::where(['user_id'=>$user_id,'consume_type'=>$breedConsume->id])->first();
                if ($record) {
                    $num = $record->num ?? 0;
                $userCoin = $userCoin+$num;
            }
            }
            
            if ($userCoin < $price) {
                throw new AppException('沐浴露余额不足');
                }
                $result = CreditPay::dopay2($params);
            }else if($pay_type ==138){  //额度支付
                $CoinQuota = BreedUserCoinQuota::where('user_id',$uid)->first();
                $Quota = $CoinQuota->num ?? 0;
                $store = Store::where('uid',$uid)->first();
                $CorpQuota = 0;
                if($store){
                    $CoinCorpQuota = HhmCoinCorpQuota::where('store_id',$store->id)
                    ->where('status',2)
                    ->where('stock_status',0)
                    ->first();
                    $CorpQuota = $CoinCorpQuota->stock_num ?? 0;
                }
                if ($Quota+$CorpQuota < $price) {
                    throw new AppException('额度余额不足');
                    }
                $result = CreditPay::dopay3($params);
            }
            else{
                $lovemember = lovemember::where('member_id',$uid)->first();
                $teaBagBalance = $lovemember->usable ?? 0;
                
                if ($teaBagBalance < $price) {
               throw new AppException('茶包余额不足');
                }
                
                $result = CreditPay::dopay($params);
        }
        
        if(!$result){
            \Log::error('[订单支付] 支付失败', ['order_id' => $order_id]);
            throw new AppException('支付失败');
        }
        
        $order->pay_time = time();
        $order->status = 1;
        $order->pay_type_id = $pay_type;
        $order->dispatch_type_id = 8;
        $order->save();
        $goods = HhmOrderGoods::where('order_id',$order->id)->get();
        foreach($goods as $item){

            // 查询商品信息
            $HhmGoods = HhmGoods::where('id', $item->goods_id)
            ->first();

            if (!$HhmGoods) {
                \Log::error("商品不存在:", ['goods_id' => $item->goods_id]);
                throw new \Exception("商品ID {$item->goods_id} 不存在");
            }
            //扣库存方式0下单1付款2永不
            $stock = $HhmGoods->stock;
            $reduce_stock_method = $HhmGoods->reduce_stock_method;
            if($reduce_stock_method==1){
                $stock = $stock-$item->total;
            }
            $HhmGoods->stock =  $stock;
            $HhmGoods->save();
        }
            
            return response()->json([
                'code' => 200,
                'message' => '支付成功',
                'data' => null
            ]);
    }
    /**
     * 获取订单列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function list()
    {
        \Log::info('[订单列表] ========== 开始获取订单列表 ==========');
        
        // 从 param 对象中获取参数
        $param = request()->input('param', []);
        $uid = $param['uid'] ?? 0;
        $status = $param['status'] ?? null; // null表示全部，0=待付款，1=待提货，3=已完成，-1=已取消
        $keyword = trim($param['keyword'] ?? '');  // 搜索关键字
        $page = $param['page'] ?? 1;
        $pageSize = $param['page_size'] ?? 10;
        
        \Log::info('[订单列表] 请求参数:', [
            'uid' => $uid,
            'status' => $status,
            'keyword' => $keyword,
            'page' => $page,
            'page_size' => $pageSize
        ]);
        
        if (!$uid) {
            return response()->json([
                'code' => 400,
                'message' => '缺少用户ID参数',
                'data' => null
            ]);
        }
        
        try {
            // 构建查询
            $query = HhmOrder::where('uid', $uid)
                ->where('is_deleted', 0);
            
            // 如果指定了状态，添加状态筛选
            if ($status !== null && $status !== '') {
                $query->where('status', $status);
            }
            
            // 关键字搜索（搜索商品名称和店铺名称）
            if (!empty($keyword)) {
                \Log::info('[订单列表] 执行关键字搜索', ['keyword' => $keyword]);
                
                $query->where(function($q) use ($keyword) {
                    // 搜索订单号
                    $q->where('order_sn', 'like', "%{$keyword}%")
                      // 或者搜索订单商品名称
                      ->orWhereHas('orderGoods', function($goodsQuery) use ($keyword) {
                          $goodsQuery->where('title', 'like', "%{$keyword}%");
                      })
                      // 或者搜索店铺名称
                      ->orWhereHas('store', function($storeQuery) use ($keyword) {
                          $storeQuery->where('store_name', 'like', "%{$keyword}%");
                      });
                });
            }
            
            // 按创建时间倒序排列
            $query->orderBy('id', 'desc');
            
            // 分页查询
            $total = $query->count();
            $orders = $query->skip(($page - 1) * $pageSize)
                ->take($pageSize)
                ->get();
            
            \Log::info('[订单列表] 查询到订单数量:', ['total' => $total, 'current_page_count' => $orders->count()]);
            
            // 格式化订单数据
            $orderList = [];
            foreach ($orders as $order) {
                // 获取订单商品
                $orderGoods = HhmOrderGoods::where('order_id', $order->id)->get();
                
                $goodsList = [];
                foreach ($orderGoods as $goods) {
                    $goodsList[] = [
                        'id' => $goods->goods_id,
                        'title' => $goods->title,
                        'thumb' => $goods->thumb,
                        'price' => (float) $goods->price,
                        'total' => $goods->total,
                        'goods_option_title' => $goods->goods_option_title ?? '',
                        'total_price' => (float) ($goods->price * $goods->total)
                    ];
                }
                
                // 获取店家信息
                $storeName = '';
                if ($order->store_id) {
                    $store = Store::where('id', $order->store_id)->first();
                    if ($store) {
                        $storeName = $store->store_name;
                    }
                }
                
                $orderList[] = [
                    'order_id' => $order->id,
                    'order_sn' => $order->order_sn,
                    'status' => $order->status,
                    'status_name' => $order->status_name,
                    'price' => (float) $order->price,
                    'goods_price' => (float) $order->goods_price,
                    'goods_total' => $order->goods_total,
                    'dispatch_price' => (float) ($order->dispatch_price ?? 0),
                    'store_id' => $order->store_id,
                    'store_name' => $storeName,
                    'create_time' => $order->created_at ? $order->created_at->timestamp : null,
                    'pay_time' => $order->pay_time,
                    'delivery_time' => $order->delivery_time,
                    'finish_time' => $order->finish_time,
                    'goods_list' => $goodsList
                ];
            }
            
            \Log::info('[订单列表] ========== 订单列表获取成功 ==========');
            
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => [
                    'list' => $orderList,
                    'total' => $total,
                    'page' => $page,
                    'page_size' => $pageSize,
                    'total_pages' => ceil($total / $pageSize)
                ]
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[订单列表] ========== 获取失败 ==========', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取订单列表失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取订单详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail()
    {
        \Log::info('[订单详情] ========== 开始获取订单详情 ==========');
        
        // 从 param 对象中获取参数
        $param = request()->input('param', []);
        $orderId = $param['order_id'] ?? 0;
        $uid = $param['uid'] ?? 0;
        
        \Log::info('[订单详情] 请求参数:', [
            'order_id' => $orderId,
            'uid' => $uid
        ]);
        
        if (!$orderId) {
            return response()->json([
                'code' => 400,
                'message' => '缺少订单ID参数',
                'data' => null
            ]);
        }
        
        try {
            // 查询订单
            $order = HhmOrder::where('id', $orderId)
                ->where('is_deleted', 0)
                ->first();
            
            if (!$order) {
                \Log::error('[订单详情] 订单不存在', ['order_id' => $orderId]);
                return response()->json([
                    'code' => 404,
                    'message' => '订单不存在',
                    'data' => null
                ]);
            }
            
            // 验证订单是否属于当前用户
            if ($uid && $order->uid != $uid) {
                \Log::error('[订单详情] 无权访问该订单', ['order_uid' => $order->uid, 'request_uid' => $uid]);
                return response()->json([
                    'code' => 403,
                    'message' => '无权访问该订单',
                    'data' => null
                ]);
            }
            
            \Log::info('[订单详情] 查询到订单', ['order_sn' => $order->order_sn]);
            
            // 获取订单商品
            $orderGoods = HhmOrderGoods::where('order_id', $order->id)->get();
            
            $goodsList = [];
            foreach ($orderGoods as $goods) {
                $goodsList[] = [
                    'id' => $goods->goods_id,
                    'title' => $goods->title,
                    'thumb' => $goods->thumb,
                    'price' => (float) $goods->price,
                    'total' => $goods->total,
                    'goods_option_title' => $goods->goods_option_title ?? '',
                    'total_price' => (float) ($goods->price * $goods->total)
                ];
            }
            
            // 获取店家信息
            $storeInfo = null;
            if ($order->store_id) {
                $store = Store::where('id', $order->store_id)->first();
                if ($store) {
                    $storeInfo = [
                        'store_id' => $store->id,
                        'store_name' => $store->store_name,
                        'store_address' => $store->store_address,
                        'store_mobile' => $store->store_mobile,
                        'full_address' => $store->full_address ?? $store->store_address
                    ];
                }
            }
            
            // 从 ims_hhm_vendor_verifiy 表中查询核销信息
            $verifyInfo = null;
            if ($order->status == 3) {
                $verifyRecord = HhmVendorVerifiy::where('type', HhmVendorVerifiy::TYPE_HHM_ORDER)
                    ->where('outbound_id', $order->id)
                    ->first();
                
                if ($verifyRecord) {
                    $verifyInfo = [
                        'verify_user_id' => $verifyRecord->user_id,
                        'verify_store_id' => $verifyRecord->store_id,
                        'verify_time' => $verifyRecord->created_at,
                        'verify_record_id' => $verifyRecord->id
                    ];
                    
                    // 获取核销门店信息
                    if ($verifyRecord->store_id) {
                        $verifyStore = Store::where('id', $verifyRecord->store_id)->first();
                        if ($verifyStore) {
                            $verifyInfo['verify_store_name'] = $verifyStore->store_name;
                            $verifyInfo['verify_store_address'] = $verifyStore->full_address ?? $verifyStore->store_address;
                        }
                    }
                    
                    // 获取核销员工信息（昵称和头像）
                    if ($verifyRecord->user_id) {
                        $verifyUser = \DB::table('ims_mc_members')
                            ->where('uid', $verifyRecord->user_id)
                            ->first();
                        if ($verifyUser) {
                            $verifyInfo['verify_user_nickname'] = $verifyUser->nickname ?? '';
                            $verifyInfo['verify_user_avatar'] = $verifyUser->avatar ?? '';
                        }
                    }
                    
                    \Log::info('[订单详情] 查询核销信息:', $verifyInfo);
                } else {
                    \Log::warning('[订单详情] 订单已完成但未找到核销记录', ['order_id' => $order->id]);
                }
            }
            
            // 组装订单详情数据
            $orderDetail = [
                'order_id' => $order->id,
                'order_sn' => $order->order_sn,
                'status' => $order->status,
                'status_name' => $order->status_name,
                'price' => (float) $order->price,
                'goods_price' => (float) $order->goods_price,
                'goods_total' => $order->goods_total,
                'dispatch_price' => (float) ($order->dispatch_price ?? 0),
                'discount_price' => (float) ($order->discount_price ?? 0),
                'store_id' => $order->store_id,
                'store_info' => $storeInfo,
                'create_time' => $order->created_at ? $order->created_at->timestamp : null,
                'pay_time' => $order->pay_time,
                'delivery_time' => $order->delivery_time,
                'finish_time' => $order->finish_time,
                'cancel_time' => $order->cancel_time,
                'remark' => $order->note ?? '',
                'goods_list' => $goodsList,
                'verify_info' => $verifyInfo  // 添加核销信息
            ];
            
            \Log::info('[订单详情] ========== 订单详情获取成功 ==========');
            
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => $orderDetail
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[订单详情] ========== 获取失败 ==========', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取订单详情失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取订单数量统计
     * @return \Illuminate\Http\JsonResponse
     */
    public function counts()
    {
        \Log::info('[订单统计] ========== 开始统计订单数量 ==========');
        
        // 从 param 对象中获取参数
        $param = request()->input('param', []);
        $uid = $param['uid'] ?? 0;
        
        \Log::info('[订单统计] 请求参数:', ['uid' => $uid]);
        
        if (!$uid) {
            return response()->json([
                'code' => 400,
                'message' => '缺少用户ID参数',
                'data' => null
            ]);
        }
        
        try {
            // 统计各状态订单数量
            $baseQuery = HhmOrder::where('uid', $uid)->where('is_deleted', 0);
            
            $counts = [
                'all' => $baseQuery->count(),
                'pending' => (clone $baseQuery)->where('status', 0)->count(),        // 待付款
                'paid' => (clone $baseQuery)->where('status', 1)->count(),           // 待提货（已支付）
                'completed' => (clone $baseQuery)->where('status', 3)->count(),      // 已完成
                'cancelled' => (clone $baseQuery)->where('status', -1)->count()      // 已取消
            ];
            
            \Log::info('[订单统计] 统计结果:', $counts);
            
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => $counts
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[订单统计] ========== 统计失败 ==========', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '统计订单数量失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取订单核销详情（用于核销页面）
     * @return \Illuminate\Http\JsonResponse
     */
    public function verificationDetail()
    {
        \Log::info('[订单核销详情] ========== 开始获取核销详情 ==========');
        
        // 从 param 对象中获取参数
        $param = request()->input('param', []);
        $orderId = $param['order_id'] ?? 0;
        $userId = $param['user_id'] ?? 0;  // 当前登录用户ID（用于权限验证）
        
        \Log::info('[订单核销详情] 请求参数:', [
            'order_id' => $orderId,
            'user_id' => $userId
        ]);
        
        if (!$orderId) {
            return response()->json([
                'code' => 400,
                'message' => '缺少订单ID参数',
                'data' => null
            ]);
        }
        
        try {
            // 查询订单
            $order = HhmOrder::where('id', $orderId)
                ->where('is_deleted', 0)
                ->first();
            
            if (!$order) {
                \Log::error('[订单核销详情] 订单不存在', ['order_id' => $orderId]);
                return response()->json([
                    'code' => 0,
                    'message' => '订单不存在',
                    'data' => null
                ]);
            }
            
            \Log::info('[订单核销详情] 查询到订单', [
                'order_sn' => $order->order_sn,
                'status' => $order->status
            ]);
            
            // 获取店家信息（用于权限验证）
            $store = null;
            if ($order->store_id) {
                $store = Store::where('id', $order->store_id)->first();
            }
            
            // 权限验证：检查当前用户是否是该店家的员工
            $hasPermission = false;
            if ($userId && $store) {
                // TODO: 这里需要检查用户是否是该店家的员工
                // 暂时简化：只要是店家主或者订单状态是已支付就有权限
                if ($store->uid == $userId || $order->status == 1) {
                    $hasPermission = true;
                }
            }
            
            \Log::info('[订单核销详情] 权限验证:', [
                'has_permission' => $hasPermission,
                'user_id' => $userId,
                'store_uid' => $store ? $store->uid : null
            ]);
            
            // 获取订单商品
            $orderGoods = HhmOrderGoods::where('order_id', $order->id)->get();
            
            $goodsList = [];
            foreach ($orderGoods as $goods) {
                $goodsList[] = [
                    'id' => $goods->goods_id,
                    'goods_id' => $goods->goods_id,
                    'name' => $goods->title,
                    'quantity' => $goods->total,
                    'price' => (float) $goods->price,
                    'image' => $goods->thumb,
                    'spec' => $goods->goods_option_title ?? ''
                ];
            }
            
            // 获取采购人（下单用户）信息
            $purchaser = Member::where('uid', $order->uid)->first();
            
            $purchaserInfo = [
                'id' => $order->uid,
                'name' => $purchaser ? $purchaser->displayName : ('用户' . $order->uid),
                'avatar' => $purchaser ? $purchaser->avatarUrl : '/static/images/default-avatar.png',
                'mobile' => $purchaser ? $purchaser->mobile : ''
            ];
            
            \Log::info('[订单核销详情] 采购人信息:', [
                'uid' => $order->uid,
                'purchaser_found' => $purchaser ? 'yes' : 'no',
                'purchaser_info' => $purchaserInfo
            ]);
            
            // 获取店家信息
            $storeInfo = null;
            if ($store) {
                $storeInfo = [
                    'store_id' => $store->id,
                    'store_name' => $store->store_name,
                    'store_address' => $store->store_address,
                    'full_address' => $store->full_address ?? $store->store_address
                ];
            }
            
            // 组装核销详情数据（返回格式与 outbound 核销保持一致）
            $verificationDetail = [
                'has_permission' => $hasPermission,
                'goods_list' => $goodsList,
                'purchaser_info' => $purchaserInfo,
                'outbound_info' => [
                    'id' => $order->id,
                    'outbound_sn' => $order->order_sn,  // 使用订单号
                    'order_sn' => $order->order_sn,
                    'status' => $order->status,
                    'status_text' => $order->status_name,
                    'created_at' => $order->created_at ? $order->created_at->timestamp : null,
                    'send_time' => $order->pay_time,
                    'finish_time' => $order->finish_time,
                    'vendor_id' => $store ? $store->uid : '',
                    'vendor_name' => $store ? $store->store_name : ''
                ],
                'store_info' => $storeInfo
            ];
            
            \Log::info('[订单核销详情] ========== 核销详情获取成功 ==========');
            
            return response()->json([
                'code' => 1,
                'message' => '成功',
                'data' => $verificationDetail
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[订单核销详情] ========== 获取失败 ==========', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '获取核销详情失败: ' . $e->getMessage(),
                'data' => null
            ]);
        }
    }

    //提货核销
    public function verifiy(){
        \Log::info('[订单核销] ========== 开始核销订单 ==========');
        
        $order_id = request()->input('param.order_id');
        $user_id = request()->input('param.user_id') ?? request()->input('param.uid');
        
        \Log::info('[订单核销] 核销参数:', [
            'order_id' => $order_id,
            'user_id' => $user_id
        ]);
        
        // ========== 1. 验证参数 ==========
        if (!$user_id) {
            \Log::error('[订单核销] 缺少用户ID');
            return response()->json([
                'code' => 400,
                'message' => '缺少用户ID',
                'data' => null
            ]);
        }
        
        // ========== 2. 查询订单 ==========
        $Order = HhmOrder::where('id',$order_id)->first();
        
        if (!$Order) {
            \Log::error('[订单核销] 订单不存在', ['order_id' => $order_id]);
            return response()->json([
                'code' => 400,
                'message' => '订单不存在',
                'data' => null
            ]);
        }
        
        // 从订单中获取 store_id
        $store_id = $Order->store_id;
        
        \Log::info('[订单核销] 订单信息:', [
            'order_id' => $order_id,
            'store_id' => $store_id,
            'order_mid' => $Order->mid,
            'order_status' => $Order->status
        ]);
        
        // ========== 3. 验证用户权限 ==========
        // 通过订单的 store_id 在 ims_hhm_staff_auth 表中查找当前用户是否有权限
        $staffAuth = StaffAuth::where('store_id', $store_id)
            ->where('uid', $user_id)
            ->where('status', StaffAuth::STATUS_AUTHORIZED)
            ->where(function($query) {
                $query->whereNull('deleted_at')
                      ->orWhere('deleted_at', 0);
            })
            ->first();
        
        if (!$staffAuth) {
            \Log::error('[订单核销] 用户无核销权限', [
                'user_id' => $user_id,
                'store_id' => $store_id
            ]);
            return response()->json([
                'code' => 403,
                'message' => '您没有该门店的核销权限',
                'data' => null
            ]);
        }
        
        \Log::info('[订单核销] 权限验证通过', [
            'user_id' => $user_id,
            'store_id' => $store_id
        ]);
        
        // ========== 4. 验证订单状态 ==========
        if($Order->status!=1){
            \Log::error('[订单核销] 订单状态不可核销', [
                'order_id' => $order_id,
                'status' => $Order->status
            ]);
            return response()->json([
                'code' => 400,
                'message' => '订单无需核销',
                'data' => null
            ]);
        }
        
        // ========== 5. 使用事务更新订单状态并记录核销信息 ==========
        try {
            DB::beginTransaction();
            
            $currentTime = time();
            
            // 更新订单状态
            $updateData = [
                'status' => 3,
                'delivery_time' => $currentTime,
                'finish_time' => $currentTime,
            ];
            
            HhmOrder::where('id', $order_id)->update($updateData);
            
            // 插入核销记录到 ims_hhm_vendor_verifiy 表
            $verifyRecord = HhmVendorVerifiy::create([
                'type' => HhmVendorVerifiy::TYPE_HHM_ORDER,  // 换换猫订单类型
                'outbound_id' => $order_id,  // 换换猫订单ID
                'user_id' => $user_id,       // 核销员工ID
                'vendor_id' => $Order->mid ?? 0,  // 供应商ID（从订单mid字段获取）
                'store_id' => $store_id,     // 核销门店ID
                'created_at' => $currentTime,
                'updated_at' => $currentTime
            ]);
            
            DB::commit();
            
            \Log::info('[订单核销] ========== 核销成功 ==========', [
                'order_id' => $order_id,
                'verify_record_id' => $verifyRecord->id,
                'verify_user_id' => $user_id,
                'verify_store_id' => $store_id,
                'verify_time' => $currentTime
            ]);
            

            //*********************结算***************/
         $store = Store::where('id',$store_id)->first();
         $pay_type = $Order->pay_type_id;
         $price = $Order->price;
         if($store){
            \Log::info('[订单核销] 查询门店结算配置', ['store_id' => $store_id, 'pay_type' => $pay_type]);
            
            $store_id = $store->id;
            $store_groupPropertie = StoreCashierSwitchCodeGroupProperties::query()   //通过支付方式找出门店对应的分组属性
            ->select(['ims_yz_store_cashier_switch_code_group_properties.*','ims_yz_store_cashier_switch_code_group_relation.settlement_num'])
            ->leftjoin('ims_yz_store_cashier_switch_code_group_relation','ims_yz_store_cashier_switch_code_group_relation.group_propertie_id','=','ims_yz_store_cashier_switch_code_group_properties.id')
            ->where('ims_yz_store_cashier_switch_code_group_relation.store_id',$store_id)
            ->where('ims_yz_store_cashier_switch_code_group_properties.in_type',$pay_type)
            ->first();
            
            \Log::info('[订单核销] 结算配置查询结果', ['found' => $store_groupPropertie ? 'yes' : 'no']);
            
            // 如果没有找到结算配置，跳过结算逻辑，直接返回支付成功
            if (!$store_groupPropertie) {
                \Log::warning('[订单核销] 未找到结算配置，跳过结算流程');
                return response()->json([
                    'code' => 200,
                    'message' => '成功',
                    'data' => null
                ]);
            }
            
         //************************************ 2025-7-1代理分成*********************/
         //2025-11-9修改需求代理分成:给代理分成的时候，不管支付方式，门店结算是什么，代理都分C款沐浴露。
            // if($pay_type ==137){
            //     $config = DistrictAgentCommissionConfig::where('id',1)->first();
            // }
            // if($pay_type ==133){
            //     $config = DistrictAgentCommissionConfig::where('id',2)->first();
            // }
            $config = DistrictAgentCommissionConfig::where('id',1)->first();
            // if($config && $config->commission_type ==1){
            if($config){
                \Log::info('[订单核销] 执行代理分成');
                // OrderCommonService::regionAgent($Order,$pay_type);
                OrderCommonService::regionAgent($Order,137); //沐浴露分成
            }
        //**************************代理分成结束*********************/
        }else {
            \Log::warning('[订单核销] 未找到门店信息，跳过结算流程');
            return response()->json([
                'code' => 200,
                'message' => '成功',
                'data' => null
            ]);
        }
        \Log::info('[订单核销] 开始门店结算', ['out_type' => $store_groupPropertie->out_type]);
        if($store_groupPropertie->out_type == 137 ){//结算沐浴露时
            \Log::info('[订单核销] 门店结算：沐浴露');
            //结算,沐浴露
            $res = (new OrderPayService())->sendUserCoin([
                'user_id' =>$store->uid,
                'order_id' => $order_id,
                'out_type_attribute' => $store_groupPropertie->out_type_attribute,
                'settlement_num' => $store_groupPropertie->settlement_num,
                'pay_type_id' =>$pay_type,
                'remark_id'=>$user_id,
            ]);
            if ($res == false) {
               \Log::error('[订单核销] 沐浴露结算失败');
               return response()->json([
                   'code' => 500,
                   'message' => '结算失败',
                   'data' => null
               ], 500);
            }
            CropQuotaService::coinReturn($store->uid,137);
        }else if($store_groupPropertie->out_type == 138)//结算额度
        {
            $num = $price * $store_groupPropertie->settlement_num/100;
            $user_id = $store->uid;
            // 查询用户额度账户
            $old_coin = 0;
            $new_coin = 0;
            $record = BreedUserCoinQuota::where('user_id',$user_id)->first();
            if($record){
                $rece_user_num = $record->num;
                $record->num = $rece_user_num + $num;
                $old_coin = $rece_user_num;
                $new_coin = $rece_user_num + $num;
                $record->save();
            }else{
                $new_coin = $num;
                BreedUserCoinQuota::create([
                    'uniacid'=>1,
                    'user_id'=>$user_id,
                    'num'=>$num,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ]);
            }
            //2、记录流水
            BreedCoinQuotaFlow::create(
                ["uniacid"=>1, 
                'send_user' => 0,
                'rec_user'=>$user_id,
                'num'=>$num,
                'type'=>4,
                'old_coin'=>$old_coin,
                'new_coin'=>$new_coin,
                'remark'=>'门店商品订单结算，订单号:'.$Order->order_sn,
                'created_at'=>time(),
                'updated_at'=>time(),
                ]
            );
            CropQuotaService::coinReturn($store->uid,138);
        }
        else{
           //结算茶包
           \Log::info('[订单核销] 门店结算：茶包');
               $usercoin = $price * $store_groupPropertie->settlement_num/100;
               \Log::info('[订单核销] 计算结算金额', ['settlement_num' => $store_groupPropertie->settlement_num, 'usercoin' => $usercoin]);
               //结算的同时更新爱心值
               $store = Store::where('id',$store_id)->first();
               if($store){
                   $uid = $store->uid;
                   $memberLove = Lovemember::where('member_id',$uid)->first();
                   $old_value = 0;
                   $change_value = $usercoin;
                   $new_value = 0;
                   if(!$memberLove){
                       Lovemember::create([
                           'uniacid' => 1,
                           'member_id' => $uid,
                           'usable' => $change_value,
                       ]);
                       $new_value = $change_value;
                   }else{
                       $old_value = $memberLove->usable;
                       $usable = $memberLove->usable + $change_value;
                       Lovemember::where('member_id',$uid)->update(['usable' => $usable]);
                       $new_value = $usable;
                   }
                   LoveRecords::create([
                       'uniacid' => 1,
                       'member_id' => $uid,
                       'old_value' => $old_value,
                       'change_value' => $change_value,
                       'new_value' => $new_value,
                       'value_type' => 1,
                       'type' => 1,
                       'source' => 18,
                       'relation' => $Order->order_sn,
                       'operator' => 2,
                       'operator_id' => $Order->uid,
                       'remark' => '订单结算',
                   ]);
                   
                   \Log::info('[订单核销] 茶包结算记录创建成功', [
                       'member_id' => $uid,
                       'change_value' => $change_value,
                       'new_value' => $new_value
                   ]);
                   CropQuotaService::coinReturn($store->uid,133);
               }
            }
            $goods = HhmOrderGoods::where('order_id',$Order->id)->get();
            foreach($goods as $item){
                $HhmGoods = HhmGoods::where('id',$item->goods_id)->first();
                $real_sales = $HhmGoods->real_sales + $item->total;
                $HhmGoods->real_sales = $real_sales;
                $HhmGoods->save();
            }
            \Log::info('[订单核销] ========== 完成 ==========');
                return response()->json([
                'code' => 200,
                'message' => '核销成功',
                'data' => [
                    'order_id' => $order_id,
                    'verify_record_id' => $verifyRecord->id,
                    'verify_time' => $currentTime,
                    'verify_user_id' => $user_id,
                    'verify_store_id' => $store_id
                ]
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            
            \Log::error('[订单核销] ========== 核销失败 ==========', [
                'order_id' => $order_id,
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '核销失败: ' . $e->getMessage(),
                'data' => null
            ]);
    }
    }

        /**
     * 获取发货号
     * @return string
     */
    public function createOrderSN()
    {
        $orderSN = CreateRandomNumber::sn('SN');
        while (1) {
            if (!HhmOrder::where('order_sn', $orderSN)->first()) {
                break;
            }
            $orderSN = CreateRandomNumber::sn('SN');
        }
        return $orderSN;
    }
}